<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<html>
<head>
    <title>修改销售记录</title>
    <style>
        /* 整体页面背景设置为浅灰色系，营造简洁科技感 */
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f5;
            margin: 0;
            padding: 0;
            color: #333;
        }

        /* 主容器样式 */
        .main-container {
            width: 80%;
            margin: 50px auto;
            padding: 30px;
            background-color: white;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border-radius: 10px;
        }

        /* 标题样式 */
        h1 {
            font-size: 30px;
            font-weight: bold;
            color: #007bff;
            margin-bottom: 20px;
        }

        /* 表单通用样式 */
        form {
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
        }

        /* 标签样式 */
        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: #333;
        }

        /* 输入框样式 */
        input[type="text"],
        input[type="number"],
        input[type="date"],
        select {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
        }

        input[type="text"]:focus,
        input[type="number"]:focus,
        input[type="date"]:focus,
        select:focus {
            border-color: #007bff;
        }

        /* 下拉菜单样式 */
        select {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23333"><path d="M7 10l5 5 5-5z"/></svg>') no-repeat right 10px center;
            background-size: 12px 12px;
        }

        /* 按钮样式 */
        input[type="submit"],
        .back-button {
            display: inline-block;
            text-decoration: none;
            padding: 12px 24px;
            border-radius: 5px;
            font-size: 18px;
            cursor: pointer;
            transition: background-color 0.3s ease,
            box-shadow: 0.3s ease;
            margin-bottom: 15px;
        }

        input[type="submit"] {
            color: white;
            background-color: #28a745;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
        }

        input[type="submit"]:hover {
            opacity: 0.8;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }

        .back-button {
            color: white;
            background-color: #6c757d;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .back-button:hover {
            opacity: 0.8;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
        }

        /* 错误信息样式 */
        .error-message {
            color: #dc3545;
            margin-bottom: 10px;
            font-size: 16px;
            display: none;
        }

        /* 按钮容器样式，将按钮放置在底部并居中 */
        .button-container {
            display: flex;
            justify-content: flex-end;
            gap: 20px;
            margin-top: 20px;
        }

        /* 只读输入框样式 */
        input[readonly] {
            background-color: #e9ecef;
            border-color: #ced4da;
            cursor: not-allowed;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        $(document).ready(function () {
            // 缓存 DOM 元素
            var $saleBillID = $('#saleBillID');
            var $saleBillIDDisplay = $('#saleBillIDDisplay');
            var $saleBillIDError = $('#saleBillIDError');
            var $goodsId = $('#goods_id');
            var $goodsIdError = $('#goodsIdError');
            var $goodsName = $('#goods_name');
            var $goodsNameError = $('#goodsNameError');
            var $saleDate = $('#sale_Date');
            var $saleDateError = $('#saleDateError');
            var $number = $('#number');
            var $numberError = $('#numberError');
            var $personId = $('#person_id');
            var $personIdError = $('#personIdError');
            var $personName = $('#person_name');
            var $personNameError = $('#personNameError');
            var $updateForm = $('#updateForm');

            // 函数：根据 ID 获取字段名称
            function updateFieldName(fieldType, id) {
                $.ajax({
                    url: 'get' + fieldType + 'NameById?id=' + id,
                    type: 'GET',
                    success: function (response) {
                        $('#' + fieldType + '_name').val(response.name);
                    },
                    error: function () {
                        console.error('Failed to fetch ' + fieldType + ' name');
                    }
                });
            }

            // 表单提交验证
            $updateForm.submit(function (e) {
                let isValid = true;
                const errorMessages = [];

                // 销售记录 ID 验证
                const saleBillID = $saleBillID.val();
                if (saleBillID !== '' && !/^[a-zA-Z0-9]{1,20}$/.test(saleBillID)) {
                    $saleBillIDError.text('销售记录 ID 必须由字母、数字组成，长度不超过 20 个字符').show();
                    errorMessages.push('销售记录 ID 必须由字母、数字组成，长度不超过 20 个字符');
                    isValid = false;
                } else {
                    $saleBillIDError.hide();
                }

                // 销售时间验证
                const saleDate = $saleDate.val();
                if (saleDate !== '' && !/^\d{4}-\d{2}-\d{2}$/.test(saleDate)) {
                    $saleDateError.text('销售时间格式应为 yyyy-MM-dd').show();
                    errorMessages.push('销售时间格式应为 yyyy-MM-dd');
                    isValid = false;
                } else {
                    $saleDateError.hide();
                }

                // 销售数量验证
                const number = $number.val();
                if (number !== '' && (!/^\d+$/.test(number) || parseInt(number) <= 0)) {
                    $numberError.text('销售数量必须为正整数').show();
                    errorMessages.push('销售数量必须为正整数');
                    isValid = false;
                } else {
                    $numberError.hide();
                }

                if (!isValid) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: '输入错误',
                        html: errorMessages.join('<br>')
                    });
                } else {
                    e.preventDefault();
                    var formData = $updateForm.serialize();
                    $.ajax({
                        url: 'saleBill.action?action=update',
                        type: 'POST',
                        data: formData,
                        success: function (response) {
                            if (response.startsWith("修改成功")) {
                                Swal.fire({
                                    icon: 'success',
                                    title: '修改成功',
                                    text: '销售信息修改成功'
                                }).then(function () {
                                    window.location.href = 'saleBill.action?action=list';
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: '修改失败',
                                    text: response
                                }).then(function () {
                                    window.location.reload();
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: '请求出错',
                                text: '出现网络问题或服务器错误，请稍后再试'
                            });
                        }
                    });
                }
            });

            // 下拉菜单的 change 事件处理
            $goodsId.on('change', function () {
                updateFieldName('goods', $(this).val());
            });

            $personId.on('change', function () {
                updateFieldName('person', $(this).val());
            });
        });
    </script>
</head>
<body>
<div class="main-container">
    <h1>修改销售记录</h1>
    <form action="saleBill.action?action=update" method="post" id="updateForm">
        <input type="hidden" id="saleBillID" name="saleBillID" value="${saleBill.saleBillID}">
        <div class="form-group">
            <label for="saleBillID">销售记录 ID</label>
            <input type="text" id="saleBillIDDisplay" name="saleBillIDDisplay" value="${saleBill.saleBillID}" readonly>
            <span class="error-message" id="saleBillIDError"></span>
        </div>
        <div class="form-group">
            <label for="goods_id">商品 ID</label>
            <select id="goods_id" name="goods_id">
                <c:forEach items="${goodsList}" var="goods">
                    <option value="${goods.id}">${goods.id}</option>
                </c:forEach>
            </select>
            <span class="error-message" id="goodsIdError"></span>
        </div>
        <div class="form-group">
            <label for="goods_name">商品名称</label>
            <input type="text" id="goods_name" name="goods_name" value="${saleBill.goods_name}" readonly>
            <span class="error-message" id="goodsNameError"></span>
        </div>
        <div class="form-group">
            <label for="sale_Date">销售时间</label>
            <input type="date" id="sale_Date" name="sale_Date"
                   value="<fmt:formatDate value="${saleBill.sale_Date}" pattern="yyyy-MM-dd"/>">
            <span class="error-message" id="saleDateError"></span>
        </div>
        <div class="form-group">
            <label for="number">销售数量</label>
            <input type="number" id="number" name="number" value="${saleBill.number}">
            <span class="error-message" id="numberError"></span>
        </div>
        <div class="form-group">
            <label for="person_id">销售人员 ID</label>
            <select id="person_id" name="person_id">
                <c:forEach items="${personList}" var="person">
                    <option value="${person.id}">${person.id}</option>
                </c:forEach>
            </select>
            <span class="error-message" id="personIdError"></span>
        </div>
        <div class="form-group">
            <label for="person_name">销售人员姓名</label>
            <input type="text" id="person_name" name="person_name" value="${saleBill.person_name}" readonly>
            <span class="error-message" id="personNameError"></span>
        </div>
        <div class="button-container">
            <input type="submit" value="提交">
            <a href="saleBill.action?action=list" class="back-button">返回</a>
        </div>
    </form>
</div>
</body>
</html>